package ssi.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ssi.tools.Connector;

/**
 * Servlet implementation class AdoptionServlet
 */
@WebServlet("/AdoptionServlet")
public class AdoptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdoptionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		String hashCode = request.getParameter("code");
		Format format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Connection connection = new Connector().getConnection();
			Statement statement = connection.createStatement();
			ResultSet result = statement.executeQuery("SELECT customerId, AnimalId FROM `adoption` WHERE `confirmation`=\""+ hashCode + "\"");
			if (result.next()) {
				int customerid = result.getInt(1);
				int animalid = result.getInt(2);
				String query = "UPDATE `adoption` SET `confirmation`='', `date`='"+format.format(Calendar.getInstance().getTime())+"' WHERE customerId="+customerid+" AND AnimalId="+animalid;
				System.out.println(query);
				statement.executeUpdate(query);
				response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
				response.setHeader("Location", "/SSIProject/index.jsp?page=adoptionSuccess");
				result.close();
				connection.close();
			} else {
				session.setAttribute("warning", "Twoj kod aktywacyjny jest zly. Skontaktuj sie z administratorem");
				response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
				response.setHeader("Location", "/SSIProject/index.jsp?page=hello");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		response.setHeader("Location", "/SSIProject/index.jsp?page=hello");
	}

}
